//
//  RegistTwoViewController.m
//  SportSocial
//
//  Created by yull on 15/1/5.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "RegistTwoViewController.h"
#import "UIColor+MethodExt.h"
#import "LoginTextField.h"
#import "UserNet.h"
#import "UIImage+resize.h"

@interface RegistTwoViewController () <UITextFieldDelegate,UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UIButton *photoButton;
@property (nonatomic, strong) LoginTextField *sexTextField;
@property (nonatomic, strong) LoginTextField *heightTextField;
@property (nonatomic, strong) LoginTextField *weightTextField;

@property (nonatomic, strong) UIImage *photoImage;

@end

@implementation RegistTwoViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.navigationController.navigationBarHidden = YES;
    
    [self initSubViews];
}

- (void)initSubViews
{
    UIImageView *backgroundImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
    backgroundImageView.image = [UIImage imageNamed:@"left_bg"];
    [self.view addSubview:backgroundImageView];
    
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    self.scrollView = scrollView;
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onClickBlank:)];
    [scrollView addGestureRecognizer:tapGesture];
    
    [self.view addSubview:scrollView];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(5, Statebar_Height + 7, 40, 40);
    [backButton setImage:[UIImage imageNamed:@"btn_back_normal"] forState:UIControlStateNormal];
    [backButton setImage:[UIImage imageNamed:@"btn_back_pressed"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(onBackButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backButton];
    
    UIButton *photoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    photoButton.frame = CGRectMake(0, Statebar_Height + 20, 95, 95);
    photoButton.centerX = self.view.width / 2;
    [photoButton setBackgroundImage:[UIImage imageNamed:@"zc_photo"] forState:UIControlStateNormal];
    [photoButton setBackgroundImage:[UIImage imageNamed:@"zc_photo_selection"] forState:UIControlStateHighlighted];
    [photoButton setTitle:@"上传头像" forState:UIControlStateNormal];
    [photoButton setTitle:@"上传头像" forState:UIControlStateHighlighted];
    [photoButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [photoButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [photoButton setTitleEdgeInsets:UIEdgeInsetsMake(48, 0, 0, 0)];
    photoButton.titleLabel.font = [UIFont systemFontOfSize:14];
    photoButton.layer.cornerRadius = photoButton.height / 2;
    photoButton.layer.masksToBounds = YES;
    [photoButton addTarget:self action:@selector(onPhotoButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:photoButton];
    self.photoButton = photoButton;
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(20, photoButton.bottom + 50, self.view.width-40, 0.5)];
    lineView.backgroundColor = [UIColor whiteColor];
    [scrollView addSubview:lineView];
    
    NSDictionary *dict = @{NSForegroundColorAttributeName:RGB(221.0f, 145.0f, 130.0f),
                           NSFontAttributeName:[UIFont boldSystemFontOfSize:18.0f]};
    
    self.sexTextField = [[LoginTextField alloc] initWithFrame:CGRectMake(20, lineView.bottom, self.view.width - 40, 60)];
    self.sexTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请选择性别" attributes:dict];
    
    UIImageView *sexImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"zc_photo_bg"]];
    self.sexTextField.leftView = sexImageView;
    self.sexTextField.leftViewMode = UITextFieldViewModeAlways;
    self.sexTextField.delegate = self;
    self.sexTextField.text = @"男";
    [scrollView addSubview:self.sexTextField];
    
    lineView = [[UIView alloc] initWithFrame:CGRectMake(20, self.sexTextField.bottom, self.view.width-40, 0.5)];
    lineView.backgroundColor = [UIColor whiteColor];
    [scrollView addSubview:lineView];
    
    self.heightTextField = [[LoginTextField alloc] initWithFrame:CGRectMake(20, lineView.bottom, self.view.width - 40, 60)];
    self.heightTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"身高" attributes:dict];
    
    UIImage *heightImage = [UIImage imageNamed:@"zc_icon4"];
    heightImage = [heightImage reSizeImageToSize:CGSizeMake(heightImage.size.width * 2, heightImage.size.height * 2)];
    UIImageView *heightImageView = [[UIImageView alloc] initWithImage:heightImage];
    self.heightTextField.leftView = heightImageView;
    self.heightTextField.leftViewMode = UITextFieldViewModeAlways;
    self.heightTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.heightTextField.returnKeyType = UIReturnKeyNext;
    self.heightTextField.delegate = self;
    [scrollView addSubview:self.heightTextField];
    
    lineView = [[UIView alloc] initWithFrame:CGRectMake(20, self.heightTextField.bottom, self.view.width-40, 0.5)];
    lineView.backgroundColor = [UIColor whiteColor];
    [scrollView addSubview:lineView];
    
    self.weightTextField = [[LoginTextField alloc] initWithFrame:CGRectMake(20, lineView.bottom, self.view.width - 120, 60)];
    self.weightTextField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"体重" attributes:dict];
    self.weightTextField.keyboardType = UIKeyboardTypeNumberPad;
    self.weightTextField.returnKeyType = UIReturnKeyDone;
    
    UIImage *weightImage = [UIImage imageNamed:@"zc_icon5"];
    weightImage = [weightImage reSizeImageToSize:CGSizeMake(weightImage.size.width * 2, weightImage.size.height * 2)];
    UIImageView *weightImageView = [[UIImageView alloc] initWithImage:weightImage];
    self.weightTextField.leftView = weightImageView;
    self.weightTextField.leftViewMode = UITextFieldViewModeAlways;
    self.weightTextField.delegate = self;
    [scrollView addSubview:self.weightTextField];
    
    lineView = [[UIView alloc] initWithFrame:CGRectMake(20, self.weightTextField.bottom, self.view.width-40, 0.5)];
    lineView.backgroundColor = [UIColor whiteColor];
    [scrollView addSubview:lineView];
    
    UIImage *buttonImage =[UIImage imageNamed:@"btn_border"];
    UIButton *completeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    completeButton.frame = CGRectMake(lineView.left, lineView.bottom + 50, self.view.width - lineView.left * 2, 40);
    [completeButton setBackgroundImage:[buttonImage stretchableImageWithLeftCapWidth:5 topCapHeight:5] forState:UIControlStateNormal];
    [completeButton setTitle:@"完成注册" forState:UIControlStateNormal];
    [completeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    completeButton.titleLabel.font = [UIFont systemFontOfSize:18.0f];
    [completeButton addTarget:self action:@selector(onCompleteButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:completeButton];
    
    scrollView.contentSize = CGSizeMake(self.view.width, MAX(self.view.height, lineView.bottom + 30));
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if ([textField isEqual:self.sexTextField]) {
        
        [self.view endEditing:YES];
        
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"请选择性别" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"男",@"女", nil];
        actionSheet.tag = 1;
        [actionSheet showInView:self.view];
        
        return NO;
    }
    return YES;
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 1) {
        if (buttonIndex == 0) {
            self.sexTextField.text = @"男";
        }else if (buttonIndex == 1) {
            self.sexTextField.text = @"女";
        }
    }else {
        if (buttonIndex == 0) {
            [self takePhoto];
        }else if (buttonIndex == 1) {
            [self pickPhoto];
        }
    }
}

- (void)onPhotoButtonClicked:(id)sender
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册", nil];
    [actionSheet showInView:self.view];
}

- (void)onCompleteButtonClicked:(id)sender
{
    //TODO：注册第二步请求接口
    [self.view endEditing:YES];
    
    if (!self.photoImage) {
        [self showText:@"请先上传头像"];
        return;
    }
    
    NSInteger sex = [self.sexTextField.text isEqualToString:@"男"] ? 0 : 1;
    [UserNet updateUserWithAddress:@""
                               sex:sex
                         signature:@""
                       friendCheck:NO
                            height:[self.heightTextField.text doubleValue]
                            weight:[self.weightTextField.text doubleValue]
                      successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
                             BOOL success = [[responseObject objectForKey:@"success"] boolValue];
                             if (success) {
                                 
                                 NSData *imageData = UIImageJPEGRepresentation(self.photoImage, 0.3f);
                                 [UserNet uploadIconWithIconData:imageData
                                                 successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
                                                     BOOL success = [[responseObject objectForKey:@"success"] boolValue];
                                                     if (success) {
                                                         [CurrentUser shareInstance].icon = [responseObject objectForKey:@"data"];
                                                         
                                                         dispatch_async(dispatch_get_main_queue(), ^{
                                                             LeftSideViewController *leftSideViewControlelr = (LeftSideViewController *)self.sideMenuViewController.leftMenuViewController;
                                                             [leftSideViewControlelr handleLoginSuccess];
                                                             [self.navigationController popToRootViewControllerAnimated:YES];
                                                             self.navigationController.navigationBarHidden = NO;
                                                         });
                                                     } else {
                                                         NSString *message = [responseObject objectForKey:@"message"];
                                                         
                                                         dispatch_async(dispatch_get_main_queue(), ^{
                                                             [self showText:message time:2];
                                                         });
                                                     }
                                                 } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
                                                     dispatch_async(dispatch_get_main_queue(), ^{
                                                         [self showText:@"网络连接失败" time:2];
                                                     });
                                                 }];
                             } else {
                                 NSString *message = [responseObject objectForKey:@"message"];
                                 
                                 dispatch_async(dispatch_get_main_queue(), ^{
                                     [self showText:message time:2];
                                 });
                             }
                             
                         } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
                             dispatch_async(dispatch_get_main_queue(), ^{
                                 [self showText:@"网络连接失败" time:2];
                             });
                         }];
}

- (void)onBackButton:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)onClickBlank:(id)sender
{
    [self.view endEditing:YES];
}

- (void)takePhoto
{
    BOOL rearCameraAvailable = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];//前
    BOOL frontCameraAvailable = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
    
    if (!rearCameraAvailable && !frontCameraAvailable) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"此设备相机不可用" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    NSUInteger sourceType = 0;//初始化调用相机相册的方法
    sourceType = UIImagePickerControllerSourceTypeCamera;//调用相册
    
    UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourceType;
    [self presentViewController:imagePickerController animated:YES completion:nil];
}

- (void)pickPhoto
{
    NSUInteger sourceType = 0;//初始化调用相机相册的方法
    sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;//调用相机
    
    UIImagePickerController * imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = sourceType;
    [self.navigationController presentViewController:imagePickerController animated:YES completion:nil];
}

//点击use调用的方法
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //要上传的图片
    self.photoImage = [info objectForKey:UIImagePickerControllerEditedImage];
    
    UIImage *image = [self.photoImage reSizeImageToSize:self.photoButton.bounds.size];
    [self.photoButton setBackgroundImage:image forState:UIControlStateNormal];
    [self.photoButton setBackgroundImage:image forState:UIControlStateHighlighted];
    [self.photoButton setTitle:nil forState:UIControlStateNormal];
    [self.photoButton setTitle:nil forState:UIControlStateHighlighted];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
//    NSData *imageData = UIImageJPEGRepresentation(image, 0.1f);
    
//    [LoginRegistNet uploadUserHeadImage:imageData successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSLog(@"上传成功!");
//    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"上传失败!");
//    }];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == self.heightTextField) {
        [self.scrollView setContentOffset:CGPointMake(0, 120) animated:YES];
    } else if (textField == self.weightTextField) {
        [self.scrollView setContentOffset:CGPointMake(0, 120) animated:YES];
    }
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    [self.scrollView setContentOffset:CGPointZero animated:YES];
    
    return YES;
}

@end
